package com.kai.admin.security.service;

import cn.hutool.core.util.IdUtil;
import com.kai.admin.security.constants.SecurityConstants;
import com.kai.admin.data.response.CaptchaResponse;
import com.kai.admin.enums.CaptchaEnum;
import com.kai.admin.util.CacheKeyRegistryUtil;
import com.wf.captcha.base.Captcha;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 验证码服务
 *
 * @author weijk
 * @since 2023/7/21
 */
@Service
public class CaptchaService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 生成验证码
     *
     * @return 验证码
     */
    public CaptchaResponse generateCaptcha(CaptchaEnum captchaType) {
        Captcha captcha = captchaType.getCaptcha();

        String key = IdUtil.fastSimpleUUID();
        String code = captcha.text();

        // 保存验证码
        saveCaptcha(key, code);

        return new CaptchaResponse()
                .setKey(key)
                .setCode(code)
                .setImage(captcha.toBase64());
    }

    /**
     * 保存验证码
     *
     * @param key 标识
     * @param code 验证码
     */
    private void saveCaptcha(String key, String code) {
        redisTemplate.opsForValue().set(CacheKeyRegistryUtil.getCaptchaKey(key), code, SecurityConstants.CAPTCHA_EXPIRATION_TIME, TimeUnit.SECONDS);
    }

    /**
     * 校验验证码
     * @param key 标识
     * @param code 验证码
     * @return true-验证码正确 false-验证码无效
     */
    public Boolean verifyCaptcha(String key, String code) {
        String captcha = redisTemplate.opsForValue().get(CacheKeyRegistryUtil.getCaptchaKey(key));
        if (StringUtils.isBlank(captcha) || !captcha.equalsIgnoreCase(code)) {
            return Boolean.FALSE;
        }

        return Boolean.TRUE;
    }

    /**
     * 删除验证码
     *
     * @param key 标识
     */
    public void deleteCaptcha(String key) {
        redisTemplate.delete(CacheKeyRegistryUtil.getCaptchaKey(key));
    }
}
